package com.example.usermanagement.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.incrementer.H2KeyGenerator;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.example.usermanagement.mybaties.MybatisPlusMetaObjectHandler;
import com.example.usermanagement.mybaties.PageInterceptor;
import com.example.usermanagement.utils.SnowflakeIdWorker;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author yha
 * @ClassName
 * @description:mybaties-plus自动配置
 * @date 2024年09月10日
 * @version: 1.0.0
 */
@Configuration
@MapperScan("com.example.usermanagement.*.mapper*")
public class MybatiesConfiguration {

    @Value("${snow.workId:1}")
    private long workId;

    @Value("${snow.dataCenterId:1}")
    private long dataCenterId;

    /**
     * 分页插件, 对于单一数据库类型来说,都建议配置该值,避免每次分页都去抓取数据库类型
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PageInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean
    public H2KeyGenerator getH2KeyGenerator() {
        return new H2KeyGenerator();
    }

    @Bean
    public SnowflakeIdWorker snowflakeIdWorker(){
        return new SnowflakeIdWorker(workId,dataCenterId);
    }

    /**
     * 审计字段自动填充
     * @return
     */
    @Bean
    public MybatisPlusMetaObjectHandler mybatisPlusMetaObjectHandler(@Qualifier(value = "snowflakeIdWorker") SnowflakeIdWorker snowflakeIdWorker) {
        return new MybatisPlusMetaObjectHandler(snowflakeIdWorker);
    }
}
